<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:images:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:images:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:images:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:images:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="imagesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <!-- 课程名展示列（带空值保护和手动匹配） -->
      <el-table-column label="课程名" align="center">
        <template slot-scope="scope">
          {{ getCourseName(scope.row.courseId) }}
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="imgUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="排序序号" align="center" prop="sort" />
      <el-table-column label="图片描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:images:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:images:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程图片管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 课程名下拉选择框（强制类型统一） -->
        <el-form-item label="课程名" prop="courseId">
          <el-select
            v-model="form.courseId"
            placeholder="请选择课程"
            clearable
            filterable
            @input="val => form.courseId = val + ''"
          >
            <el-option
              v-for="course in coursesList"
              :key="course.id"
              :label="course.title"
              :value="course.id + ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl">
          <image-upload v-model="form.imgUrl"/>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序序号" />
        </el-form-item>
        <el-form-item label="图片描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入图片描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listImages, getImages, delImages, addImages, updateImages } from "@/api/course/images"
import { listCourses } from "@/api/course/courses"

export default {
  name: "Images",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程图片管理表格数据
      imagesList: [],
      // 课程列表（用于下拉选择和名称匹配）
      coursesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数（courseId强制字符串类型）
      form: {
        id: null,
        courseId: "",
        imgUrl: null,
        sort: null,
        description: null
      },
      // 表单校验
      rules: {
        courseId: [
          { required: true, message: "课程名不能为空", trigger: "blur" }
        ],
        imgUrl: [
          { required: true, message: "图片不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序序号不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getCoursesList() // 加载课程列表
  },
  methods: {
    /** 查询课程图片管理列表 */
    getList() {
      this.loading = true
      listImages(this.queryParams).then(response => {
        this.imagesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 获取所有课程列表（统一ID为字符串类型） */
    getCoursesList() {
      listCourses({ pageNum: 1, pageSize: 1000 }).then(response => {
        // 强制将课程ID转为字符串，确保类型一致
        this.coursesList = response.rows.map(course => ({
          ...course,
          id: course.id + '',  // 转为字符串
          title: course.title || '未知课程'
        }))
      }).catch(error => {
        console.error("获取课程列表失败：", error)
        this.$message.error("获取课程列表失败，请刷新重试")
      })
    },

    /** 根据课程ID手动匹配课程名称（解决关联失败问题） */
    getCourseName(courseId) {
      if (!courseId) return '-'

      // 统一查询ID为字符串类型
      const targetId = courseId + ''
      // 在课程列表中查找匹配项
      const course = this.coursesList.find(item => item.id === targetId)

      return course ? course.title : `未知课程(${courseId})`
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        courseId: "",
        imgUrl: null,
        sort: null,
        description: null
      }
      this.resetForm("form")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加课程图片管理"
    },

    /** 修改按钮操作（强制转换courseId为字符串） */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getImages(id).then(response => {
        const data = response.data
        this.form = {
          ...data,
          // 强制转换为字符串，确保与下拉框选项匹配
          courseId: data.courseId + ''
        }
        this.open = true
        this.title = "修改课程图片管理"
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateImages(this.form).then(() => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addImages(this.form).then(() => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm(`是否确认删除课程图片管理编号为"${ids}"的数据项？`).then(() => {
        return delImages(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('course/images/export', {
        ...this.queryParams
      }, `images_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
